﻿using Networks;
using Newtonsoft.Json.Linq;
using Pomelo.DotNetClient;
using System;
using UnityEngine;
using UnityEngine.UI;

namespace game.login
{
    public class Login : MonoBehaviour
    {
        [Header("UI")]
        public InputField name_InputField;
        public Button login_btn;

        [Header("Server")]
        private string host = "192.168.10.254";
        private int port = 3014;

        private PomeloClient _pclient;

        private void Start()
        {
            login_btn.onClick.AddListener(login);
        }

        private void OnApplicationQuit()
        {
            _pclient?.disconnect();
        }

        private void login()
        {
            if (string.IsNullOrEmpty(name_InputField.text))
            {
                return;
            }

            Debug.Log("Connecting to gate server: " + host + ":" + port);

            _pclient = new PomeloClient();
            //_pclient.NetWorkStateChangedEvent += (state) =>
            //{
            //    Debug.Log("state changed " + state);
            //};

            _pclient.initClient(host, port, () =>
            {
                //Debug.Log("PomeloClient.initClient callback.");

                _pclient.connect(data =>
                {
                    //Debug.Log("PomeloClient.connect callback.");

                    JObject msg = new JObject();
                    msg["uid"] = name_InputField.text;
                    _pclient.request(Routes.GATE_CONNECT, msg, onConnect);
                });
            });
        }

        private void onConnect(JObject response)
        {
            //Debug.Log("onConnect called. Acquired data from gate server.");

            if (Convert.ToInt32(response["code"]) == (int)Networks.GAME.RETURN_CODE.SUCCESS)
            {
                _pclient?.disconnect();
                _pclient = null;

                // myself
                Game.Instance.myself.username = name_InputField.text;

                string connectorHost = response["host"].ToString();
                int connectorPort = Convert.ToInt32(response["port"]);
                Debug.Log("Connecting to connector server: " + connectorHost + ":" + connectorPort);

                JObject user = new JObject();
                user.Add("uid", name_InputField.text);
                NetworkManager.Instance.InitClient(connectorHost, connectorPort, user);
            }
            else
            {
                Debug.Log("Connection error.");
            }
        }
    }
}